package top.kpromise.user.service_imp;

import org.springframework.stereotype.Service;
import top.kpromise.user.data.Config;
import top.kpromise.user.mapper.UserTicketMapper;
import top.kpromise.user.model.response.UserTicketModel;
import top.kpromise.user.response.Result;
import top.kpromise.user.service.UserTicketService;
import top.kpromise.user.utils.DateUtils;

import java.util.Date;
import java.util.Map;

@Service
public class UserTicketServiceImp implements UserTicketService {

    private final UserTicketMapper userTicketMapper;

    public UserTicketServiceImp(UserTicketMapper userTicketMapper) {
        this.userTicketMapper = userTicketMapper;
    }

    @Override
    public int insert(UserTicketModel userTicketModel) {
        return userTicketMapper.insert(userTicketModel);
    }

    @Override
    public int update(UserTicketModel userTicketModel) {
        return userTicketMapper.update(userTicketModel);
    }

    @Override
    public UserTicketModel findByTicket(String ticket) {
        return userTicketMapper.findByTicket(ticket);
    }

    @Override
    public UserTicketModel findByUserIdAndType(String userId, int type) {
        return userTicketMapper.findByUserIdAndType(userId, type);
    }

    @Override
    public int deleteByTicket(String ticket) {
        return userTicketMapper.deleteByTicket(ticket);
    }

    @Override
    public void saveTicket(UserTicketModel userTicketModel) {
        UserTicketModel oldResult = findByUserIdAndType(userTicketModel.getUserId(), userTicketModel.getType());
        userTicketModel.setUpdateAt(DateUtils.currentDate());
        if (oldResult != null) {
            update(userTicketModel);
        }else {
            insert(userTicketModel);
        }
    }

    @Override
    public Map<String, Object> checkTicket(String ticket, String userId, int type) {
        UserTicketModel userTicketModel = findByTicket(ticket);
        if (userTicketModel == null) {
            return Result.data(null, "Ticket不存在");
        }
        if (!userTicketModel.getUserId().equals(userId) || userTicketModel.getType() != type) {
            return Result.data(null, "Ticket错误");
        }
        long now = DateUtils.currentDate().getTime();
        Date created = DateUtils.currentDate(userTicketModel.getUpdateAt());
        if (created == null) {
            return Result.data(null, "已超时，请重新操作");
        }
        long createdAt = created.getTime();
        if (now - createdAt > Config.TICKET_TIME_OUT) {
            return Result.data(null, "已超时，请重新操作");
        }
        return null;
    }
}
